package app

import (
	"fmt"
	"os"
	"strings"
	"v3workshop/pkg/parcel"
	"v3workshop/pkg/uix"
	"v3workshop/pkg/util"
)

type MergeOption struct {
	Force bool
}

func (m *Manager) Merge(opt *MergeOption) error {
	err := m.LoadConfig()
	if err != nil {
		return err
	}
	err = m.LoadParcels()
	if err != nil {
		return err
	}
	data := make([]string, 0, len(m.Parcels))
	for _, p := range m.Parcels {
		item := []string{p.Id}
		if p.Metadata != nil {
			item = append(item, p.Metadata.Name, p.Metadata.Version, p.Metadata.ShortDescription)
		}
		data = append(data, strings.Join(item, " | "))
	}
	indexList, err := uix.SelectMulti("Select parcel to merge", data)
	if err != nil {
		return err
	}
	parcels := make([]*parcel.Parcel, 0, len(indexList))
	for _, i := range indexList {
		parcels = append(parcels, m.Parcels[i])
	}
	err = m.mergeParcels(parcels, opt.Force)
	if err != nil {
		return err
	}
	return nil
}

func (m *Manager) mergeParcels(parcels []*parcel.Parcel, force bool) error {
	if force {
		_ = os.RemoveAll(m.Config.TargetPath)
	}
	if util.IsFileExists(m.Config.TargetPath) {
		return fmt.Errorf("target path already exists")
	}
	err := os.MkdirAll(m.Config.TargetPath, os.ModePerm)
	if err != nil {
		return err
		
	}
	for _, p := range parcels {
		err = p.CopyToPath(m.Config.TargetPath)
		if err != nil {
			return err
		}
	}
	return nil
}
